// (C) 2021 Intel Corporation. All rights reserved.
// Your use of Intel Corporation's design tools, logic functions and other 
// software and tools, and its AMPP partner logic functions, and any output 
// files from any of the foregoing (including device programming or simulation 
// files), and any associated documentation or information are expressly subject 
// to the terms and conditions of the Intel Program License Subscription 
// Agreement, Intel FPGA IP License Agreement, or other applicable 
// license agreement, including, without limitation, that your use is for the 
// sole purpose of programming logic devices manufactured by Intel and sold by 
// Intel or its authorized distributors.  Please refer to the applicable 
// agreement for further details.

`default_nettype none

//////////////////////////////////////////////////////////////////////////////////
//          Delay
//////////////////////////////////////////////////////////////////////////////////
module delay #
(
                                // Total count
    parameter                   COUNT  =   1
)
(
                                // Clock Input
    input wire                  iClk,
                                // Asynchronous Reset Input
    input wire                  iRst,
                                // Start Delay Input Signal
    input wire                  iStart,
                                //%Clear Count signal
    input wire                  iClrCnt,
                                // Done Flag Output
    output wire                 oDone
);

   
localparam TOTAL_BITS = clog2(COUNT);

reg                     rDone;
reg [(TOTAL_BITS-1):0]  rCount;

always @(posedge iClk or negedge iRst)
begin
	if (~iRst) begin						//Reset
		rDone   <=   1'b0;					//Done flag
		rCount  <=   {TOTAL_BITS{1'b0}};	//Counter
	end
	else begin
		if(~iStart || iClrCnt) begin		//If iStart is LOW or iClrCnt is HIGH, output goes low as well
			rDone	<= 1'b0;
			rCount	<= {TOTAL_BITS{1'b0}};
		end
		else if (COUNT-1 > rCount) begin	//Output set as high when counter reaches expected value
			rDone	<= 1'b0;
			rCount	<= rCount + 1'b1;
		end
		else begin							//Output low and counter increases if no conditions were met
			rDone	<= 1'b1;
			rCount	<= rCount;
		end
	end
end

assign oDone = rDone;

function integer clog2;
input integer value;
begin
   value = (value > 1) ? value-1 : 1;
   for (clog2=0; value>0; clog2=clog2+1)
     value = value>>1;
end

endfunction

endmodule
